<!-- 组件说明 -->
<template>
  <div class='add'>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb> 
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 整个表单区域 -->
      <el-form :model="addGoodsForm" label-position="top" :rules="addFormRules" ref="addGoodsForm" label-width="100px">
        <!-- 选项卡区域 -->
        <el-tabs tab-position="left" :before-leave="beforeTapLeave" @tab-click="tapClicked" v-model="activeIndex">
          <!-- 基本信息区域 -->
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addGoodsForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addGoodsForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addGoodsForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联器区域 -->
              <el-cascader v-model="addGoodsForm.goods_cat" :options="cascaderList" :props="cascaderProps" @change="cascaderChange"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数区域 -->
          <el-tab-pane name="1" label="商品参数">
            <!-- 渲染表单的Item项 -->
            <el-form-item v-for="item in paramsList" :label="item.attr_name" :key="item.attr_id">
              <!-- 多选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for=" (i,index) in item.attr_vals"  :label="i" :key="index"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性区域 -->
          <el-tab-pane name="2" label="商品属性">
            <el-form-item v-for="item in attrList" :label="item.attr_name" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品图片区域 -->
          <el-tab-pane name="3" label="商品图片">
            <!-- 文件上传区域 -->
            <!-- action：图片上传地址 -->
            <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove"
              :headers="headerObj" list-type="picture" :on-success="handleSuceess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <!-- 商品内容区域 -->
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addGoodsForm.goods_introduce">
            </quill-editor>
            <!-- 添加商品按钮 -->
            <el-button size="mini" type="primary" class="addGoodBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <!-- 预览图片对话框 -->
      <el-dialog title="图片预览" :visible.sync="previewPicDialogVisible" width="50%">
        <img :src="previewPath" alt="" class="previewImg">
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  //import x from ''
  // lodash库
  import _ from 'lodash'
 
  export default {
    components: {

    },
    data () {
      return {
        //步骤条 当前步骤位置
        activeIndex: 0,
        // 表单内容绑定
        addGoodsForm: {
          goods_name: '',
          goods_price: 0,
          goods_number: 0,
          goods_weight: 0,
          //商品所属的分类数组
          goods_cat: [],
          //上传成功图片数组
          pics: [],
          //商品介绍内容
          goods_introduce: '',
          // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
          attrs: []
        },
        //表单验证规则
        addFormRules: {
          goods_name:[
             { required: true, message: '请输入商品名称', trigger: 'blur' },
          ],
          goods_price:[
             { required: true, message: '请输入商品价格', trigger: 'blur' },
          ],
          goods_number:[
             { required: true, message: '请输入商品数量', trigger: 'blur' },
          ],
          goods_weight:[
             { required: true, message: '请输入商品重量', trigger: 'blur' },
          ],
          goods_cat:[
             { required: true, message: '请输入商品介绍', trigger: 'blur' },
          ],
        },
        //级联器展示内容
        cascaderList:[],
        //级联器属性配置
        cascaderProps:{
          expandTrigger: 'hover',
          label: 'cat_name',
          value: 'cat_id',
          children: 'children'
        },
        //参数列表数据
        paramsList:[],
        //动态参数列表
        checkList: [],
        //静态属性列表
        attrList: [],
        //上传图片地址
        uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
        //上传图片请求头
        headerObj: {
          Authorization: window.sessionStorage.getItem('token')
        },
        //上传成功图片存储路径
        tmp_path: '',
        //预览图片路径
        previewPath: '',
        //显示or隐藏预览图片对话框
        previewPicDialogVisible:false
      };
    },
    computed: {
      cateId(){
        if(this.addGoodsForm.goods_cat.length == 3){
          return this.addGoodsForm.goods_cat[2]
        }else{
          return null
        }
        
      }
    },
    created() {
      this.getCascaderList()
    },
    methods: {
      //监听级联器选项改变事件
      cascaderChange(){
        console.log(this.addGoodsForm.goods_cat);
        if(this.addGoodsForm.goods_cat.length !== 3){
          this.addGoodsForm.goods_cat = []
        }
      },
      //获取级联器内容列表
      async getCascaderList(){
        const{data:res} = await this.$http.get("categories")
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg)
        }else{
          this.cascaderList = res.data
          console.log(this.cascaderList);
        }
      },
      //切换选项卡 检查当前内容是否完成且符合规定
      beforeTapLeave(activeName,oldActiveName){
        // console.log("即将进入的选项卡index"+activeName);
        // console.log("即将离开的选项卡index"+oldActiveName);
        if(oldActiveName === '0'  && this.addGoodsForm.goods_cat.length !== 3 ){
          this.$message.error("请先选择商品三级分类")
          return false 
        }
      },
      //监听点击选项卡事件
      async tapClicked(){
        console.log(this.activeIndex);
        //访问动态参数面板 
        if (this.activeIndex === '1') {
          console.log("动态参数面板");
          const{data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params: {sel: "many"}})
          if(res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }else{
            res.data.forEach((item) => {
              item.attr_vals ? item.attr_vals = item.attr_vals.split(','):[]
            })
            this.paramsList = res.data
            console.log(this.paramsList);
          }
        }
        //访问商品属性选项卡
        if (this.activeIndex === '2') {
          console.log("静态属性面板");
          const{data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params: {sel: "only"}})
          if(res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }else{
            this.attrList = res.data
            console.log(this.attrList);
          }
        }
        // 访问商品图片选项卡
        if (this.activeIndex === '3') {
          console.log("商品图片面板");
        }
      },
      //处理图片预览业务逻辑
      handlePreview(file){
        console.log(file);
        this.previewPath = file.response.data.url
        this.previewPicDialogVisible = true
      },
      //处理移除图片操作
      handleRemove(file){
        let filePath = file.response.data.tmp_path
        let index = this.addGoodsForm.pics.findIndex(x => {
          x.pic === filePath
        })
        this.addGoodsForm.pics.splice(index,1)
      },
      //文件上传成功回调函数
      handleSuceess(response){
        //拼接得到一个图片信息对象
        const picInfo = {pic: response.data.tmp_path}
        this.addGoodsForm.pics.push(picInfo)
      },
      // 监听添加商品按钮点击事件
      addGoods(){
        this.$refs.addGoodsForm.validate(async valid => {
          if(!valid){
            return this.$meaage.error("请完整填写相关内容")
          }else{
            console.log(this.addGoodsForm);
            let copyForm = _.cloneDeep(this.addGoodsForm)
            copyForm.goods_cat = copyForm.goods_cat.join(',')
            // 处理动态参数
            this.paramsList.forEach((item) => {
              const newInfo = {attr_id: item.attr_id,attr_value: item.attr_vals.join(',')}
              this.addGoodsForm.attrs.push(newInfo)
            })
            // 处理静态属性 
            this.attrList.forEach(item =>{
              const newInfo = {attr_id: item.attr_id,attr_value: item.attr_vals}
              this.addGoodsForm.attrs.push(newInfo)
            })
            copyForm.attrs = this.addGoodsForm.attrs
            // 发起添加商品请求 
            //商品的名称必须是唯一的
            const{data:res} = await this.$http.post(`goods`,copyForm)
            if(res.meta.status !== 201) {
              return this.$message.error(res.meta.msg)
            }else{
              this.$message.success("添加商品成功")
              this.$router.push('/goods')
            }
          }
        })
        
      }



      
    },
  }
</script>

<style lang='less' scoped>
//@import url()
.el-steps{
  margin-top: 15px;
}

.el-tabs{
  margin-top: 20px;
}
.el-checkbox{
  margin: 0px 10px 0px 0px !important;
}
.previewImg{
  width: 100%;
}

.addGoodBtn{
  margin-top: 15px;
}
</style>